<template>
  <div>
    <div class="content-goods-publish">
      <el-form :label-width="120" ref="saveRef" :model="baseInfoForm" :rules="baseInfoFormRule">
        <div class="base-info-item">
          <h4>基本信息</h4>
          <div class="form-item-view">
            <el-form-item label="商品分类">
              <span class="goods-category-name">{{
                  baseInfoForm.categoryName[0]
                }}</span>
              <span> &gt; {{ baseInfoForm.categoryName[1] }}</span>
            </el-form-item>
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="baseInfoForm.name" clearable placeholder="商品名称" style="width: 260px"
                        type="text"/>
            </el-form-item>
            <el-form-item label="商品价格" prop="spuPrice">
              <el-input v-model="baseInfoForm.spuPrice" clearable placeholder="商品价格" style="width: 260px"
                        type="text"/>
            </el-form-item>
            <el-form-item label="商品描述" prop="des">
              <el-input v-model="baseInfoForm.des" :rows="4" style="width: 260px" type="textarea"/>
            </el-form-item>
            <el-form-item label="商品品牌" prop="brandId">
              <el-select v-model="baseInfoForm.brandId" style="width: 200px" clearable>
                <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="基础属性" prop="spuAttrValueAddRequest">
              <div v-for="(attr,index) in  spuAttrKeyList" :key="index">
                {{ attr.keyName }}:
                <el-input type="text" v-model="attr.value" placeholder="请输入"/>
              </div>
            </el-form-item>
            <el-form-item class="form-item-view-el required" label="下拉介绍图" prop="spuImageAddRequest">
              <el-upload
                  :limit="6"
                  action="#"
                  list-type="picture-card"
                  :on-exceed="handleExceed"
                  v-model:file-list="fileList"
                  :on-change="uploadImg"
                  :auto-upload="false"
                  accept="image/jpg,image/jpeg,image/png,image/webp"
              >
                <el-icon>
                  <Plus/>
                </el-icon>
                <template #file="{ file }">
                  <div>
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
                    <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
            <el-icon><zoom-in/></el-icon>
          </span>
          <span class="el-upload-list__item-delete" @click="handleRemove(file)">
            <el-icon><Delete/></el-icon>
          </span>
        </span>
                  </div>
                </template>
                <template #tip>
                  <div class="el-upload__tip"> 可以上传6张照片，单个不超过2M</div>
                </template>
              </el-upload>
              <!--              // 预览弹窗
                            <el-dialog append-to-body v-model="dialogVisible">
                              <img width="100%" :src="state.dialogImageUrl" alt=""/>
                            </el-dialog>-->
            </el-form-item>
          </div>
        </div>
        <div class="base-info-item">
          <h4>sku信息</h4>
          <el-button @click="addObject()">添加sku</el-button>
          <el-button @click="removeObject()">移除sku</el-button>
          <div v-for="(sku, index) in baseInfoForm.goodsSkuAddRequest">
            <h3>SKU {{ index + 1 }}</h3>
            <el-form-item label="sku原价" prop="skuOldPrice">
              <el-input v-model="sku.skuOldPrice" placeholder="sku原价" type="text"></el-input>
            </el-form-item>
            <el-form-item label="sku现价" prop="skuPrice">
              <el-input v-model="sku.skuPrice" placeholder="现价" type="text"></el-input>
            </el-form-item>
            <el-form-item label="商品库存" prop="stock">
              <el-input v-model="sku.stock" placeholder="库存" type="text"></el-input>
            </el-form-item>
            <el-form-item label="排序" prop="skuSort">
              <el-input v-model="sku.skuSort" placeholder="排序" type="text"></el-input>
            </el-form-item>
            <el-form-item label="销售属性" prop="skuAttrKeyList">
              <div v-for="(attr,indexA) in  skuAttrKeyList" :key="indexA">
                {{ attr.keyName }}:
                <el-input type="text" v-model="attr.value" placeholder="请输入"/>
              </div>
            </el-form-item>
            <el-form-item class="form-item-view-el required" label="对应sku图片" prop="skuImageAddRequest">
              <el-upload
                  :limit="6"
                  action="#"
                  list-type="picture-card"
                  :on-exceed="handleExceedSku"
                  v-model:file-list="fileListSku"
                  :on-change="uploadImgSku"
                  :auto-upload="false"
                  accept="image/jpg,image/jpeg,image/png,image/webp"
              >
                <el-icon>
                  <Plus/>
                </el-icon>
                <template #file="{ file }">
                  <div>
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
                    <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePictureCardPreviewSku(file)">
            <el-icon><zoom-in/></el-icon>
          </span>
          <span class="el-upload-list__item-delete" @click="handleRemoveSku(file)">
            <el-icon><Delete/></el-icon>
          </span>
        </span>
                  </div>
                </template>
                <template #tip>
                  <div class="el-upload__tip"> 可以上传6张照片，单个不超过2M</div>
                </template>
              </el-upload>
              <!--              // 预览弹窗
                            <el-dialog append-to-body v-model="dialogVisible">
                              <img width="100%" :src="state.dialogImageUrl" alt=""/>
                            </el-dialog>-->
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <!-- 底部按钮 -->
    <div class="footer">
      <el-button type="primary" @click="pre">上一步</el-button>
      <el-button :loading="submitLoading" type="primary" @click="save">
        {{ this.$route.query.id ? "保存" : "保存商品" }}
      </el-button>
    </div>
  </div>
</template>
<script setup>
import {ElMessage} from "element-plus";
import {Delete, Plus, ZoomIn} from "@element-plus/icons";
import {onMounted, reactive, ref, watch} from "vue";
import {useStore} from "vuex";
import {getBrandByCateId} from "@/api/brandManage.js";
import {getAttrKeyAPI} from "@/api/attrKeyManage.js";
import {uploadFileAPI} from "@/api/fileManage.js";
import {addGoodsAPI} from "@/api/goodsManage.js";
const len = ref(1)

const emit = defineEmits(['pre','nextOne']);

function pre() {
  emit('pre');
}

const props = defineProps({
  firstData: {
    default: {},
    type: Object,
  },
});
const baseInfoForm = ref({
  categoryId: '',
  categoryParentId: '',
  name: '',
  categoryName: [],
  brandId: '',
  spuPrice: '',
  spuAttrValueAddRequest: [{
    keyId: '',
    keyName: "",
    value: ""
  }],
  spuImageAddRequest: [{
    image: "",
    des: "",
    sort: 0
  }],
  goodsSkuAddRequest: [{
    skuOldPrice: "",
    skuPrice: "",
    skuStatus: "",
    skuDiscount: "wu",
    stock: "",
    skuSort: 0,
    skuAttrValueAddRequest: [
      {
        keyId: '',
        keyName: "",
        value: ""
      }
    ],
    skuImageAddRequest: [
      {
        image: "",
        sort: '',
        des: ""
      },
    ]
  }]
})
watch(() => baseInfoForm.value.goodsSkuAddRequest.length, (newLength, oldLength) => {
  // 处理数组长度变化的逻辑
  len.value = newLength
  console.log(`数组长度从 ${oldLength} 变为 ${newLength}`);
});
//对应品牌
const brandList = ref([])
//对应属性key
const attrKeyList = ref([])
//对应基本属性key
const spuAttrKeyList = ref([])

const skuAttrKeyListIndex = ref([])
//对应销售属性key
const skuAttrKeyList = ref([])
const store = useStore();
// 编辑时获取商品信息
const getGoodsBasicData = async () => {
  const data = ref(props.firstData);
  if (data.value.category) {
    const cateId = [];
    data.value.category.forEach((cate) => {
      baseInfoForm.value.categoryName.push(cate.name);
      cateId.push(cate.id);
    });
    console.log("data.value.category", baseInfoForm.value.categoryName)
    baseInfoForm.value.categoryId = cateId[1]
    baseInfoForm.value.categoryParentId = cateId[0]
    /** 查询品牌列表 */
    await getGoodsBrandList(cateId[1]);
    /*获取对应的属性key信息*/
    await getAttrList(cateId[1])
  }
}
/** 查询品牌列表 */
const getGoodsBrandList = async (cateId) => {
  const res = await getBrandByCateId(cateId)
  brandList.value = res.data
}
/** 获取对应的属性key信息 */
const getAttrList = async (cateId) => {
  const res = await getAttrKeyAPI({categoryId: cateId})
  attrKeyList.value = res.data.records
  spuAttrKeyList.value = attrKeyList.value.filter(attr => attr.attrType === 1)
  skuAttrKeyListIndex.value = attrKeyList.value.filter(attr => attr.attrType === 0)
  /*skuAttrKeyList.value.push(skuAttrKeyListIndex.value)*/
  skuAttrKeyList.value =  attrKeyList.value.filter(attr => attr.attrType === 0)
}
/*商品添加数据校验*/
const baseInfoFormRule = {
  name: [
    {required: true, message: '名称不能为空', trigger: 'blur'}
  ],
  des: [{required: true, message: '描述不能为空', trigger: 'blur'}],
  spuPrice: [{required: true, message: '价格不能为空', trigger: 'blur'}],
  brandId: [{required: true, message: '品牌不能为空', trigger: 'blur'}],
  spuAttrValueAddRequest: [{required: true, message: '基础属性不能为空', trigger: 'blur'}],
}

onMounted(async () => {
  await getGoodsBasicData()
})
/*图片上传*/
let dialogVisible = ref(false);
let fileList = ref([])
const picList = ref([])
let fileListSku = ref([])
const picListSku = ref([])
const state = reactive({
  photoList: [],
  dialogImageUrl: '',
})
const stateSku = reactive({
  photoList: [],
  dialogImageUrl: '',
})

// 上传文件
const uploadImg = async (file) => {
  // 单个文件大小不能超过2M
  let fileSize = file.size / 1024;
  let maxSize = 1024 * 2;
  if (fileSize > maxSize) {
    ElMessage({
      message: '单个文件最大2M',
      type: 'warning',
    });
    return;
  }
  // 创建 FormData 对象
  const formData = new FormData();
  // 将文件添加到 FormData 中
  formData.append('file', file.raw);
  const res = await uploadFileAPI(formData)
  if (res.data) {
    state.photoList.push(res.data);
    ElMessage.success("上传成功")
  }
  const params = ref({
    image: res.data,
    des: "",
    sort: fileList.value.length - 1
  })
  picList.value.push(params.value)
};

const uploadImgSku = async (file) => {
  // 单个文件大小不能超过2M
  let fileSize = file.size / 1024;
  let maxSize = 1024 * 2;
  if (fileSize > maxSize) {
    ElMessage({
      message: '单个文件最大2M',
      type: 'warning',
    });
    return;
  }
  // 创建 FormData 对象
  const formData = new FormData();
  // 将文件添加到 FormData 中
  formData.append('file', file.raw);
  const res = await uploadFileAPI(formData)
  if (res.data) {
    stateSku.photoList.push(res.data);
    ElMessage.success("上传成功")
  }
  const params = ref({
    image: res.data,
    des: "",
    sort: fileListSku.value.length - 1
  })
  picListSku.value.push(params.value)
};

// 删除
const handleRemove = (file) => {
  const index = fileList.value.indexOf(file);
  fileList.value.splice(index, 1);
  state.photoList = state.photoList.filter((item) => item.fileName !== file.name);
  //真正发到后端的数据也要处理
  picList.value.splice(index, 1)
};
// 删除Sku
const handleRemoveSku = (file) => {
  const index = fileListSku.value.indexOf(file);
  fileListSku.value.splice(index, 1);
  stateSku.photoList = stateSku.photoList.filter((item) => item.fileName !== file.name);
  //真正发到后端的数据也要处理
  picListSku.value.splice(index, 1)
};

// 预览
const handlePictureCardPreview = (file) => {
  console.log("file", file)
  state.dialogImageUrl = file.url;
  dialogVisible.value = true;
};

const handlePictureCardPreviewSku = (file) => {
  console.log("file", file)
  stateSku.dialogImageUrl = file.url;
  dialogVisible.value = true;
};

// 上传照片超出限制的提示
const handleExceed = () => {
  ElMessage({
    message: '最多上传6张照片',
    type: 'warning',
  });
};
const handleExceedSku = () => {
  ElMessage({
    message: '最多上传6张照片',
    type: 'warning',
  });
};
//sku动态生成
// 添加对象
const addObject = () => {
  baseInfoForm.value.goodsSkuAddRequest.push({
    skuOldPrice: 1249.00,
    skuPrice: 1249.00,
    skuStatus: 1,
    skuDiscount: "wu",
    stock: 200,
    skuSort: 0,
    skuAttrValueAddRequest: [
      {
        keyId: '',
        keyName: "",
        value: ""
      }
    ],
    skuImageAddRequest: [
      {
        image: "",
        sort: '',
        des: ""
      },
    ]
  });
  let index = skuAttrKeyListIndex.value
  skuAttrKeyList.value.push(index)
  console.log("skuAttrKeyList.value",skuAttrKeyList.value)
};
// 删除对象
const removeObject = () => {
  baseInfoForm.value.goodsSkuAddRequest.pop();
};
//商品添加
const saveRef = ref()
const save = () => {
  //spu信息
  baseInfoForm.value.spuAttrValueAddRequest = spuAttrKeyList.value
  //spu图片
  baseInfoForm.value.spuImageAddRequest = picList.value;
  //sku的属性信息
  console.log("skuAttrKeyList.value",skuAttrKeyList.value)
  //目前支持一个sku添加
  baseInfoForm.value.goodsSkuAddRequest[0].skuAttrValueAddRequest = skuAttrKeyList.value;
  baseInfoForm.value.goodsSkuAddRequest[0].skuImageAddRequest = picListSku.value;
  console.log("baseInfoForm.value", baseInfoForm.value)
  saveRef.value.validate(async (valid) => {
     if (valid) {
       const res = await addGoodsAPI(baseInfoForm.value)
       if (res.data) {
         emit('nextOne');
         ElMessage.success("添加成功")
       }
     }
  })
}

</script>
<style lang="scss" scoped>
@import "./addGoods.scss";
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

<style scoped>
.ivu-select .ivu-select-dropdown {
  overflow: hidden !important;
}

#dplayer {

}

.refresh-icon {
  margin-left: 10px;
}

</style>
